# OS Name (Linux or Darwin)
OSUPPER = $(shell uname -s 2>/dev/null | tr [:lower:] [:upper:])
OSLOWER = $(shell uname -s 2>/dev/null | tr [:upper:] [:lower:])

# Flags to detect 32-bit or 64-bit OS platform
OS_SIZE = $(shell uname -m | sed -e "s/i.86/32/" -e "s/x86_64/64/")
OS_ARCH = $(shell uname -m | sed -e "s/i386/i686/")

# These flags will override any settings
ifeq ($(i386),1)
	OS_SIZE = 32
	OS_ARCH = i686
endif

ifeq ($(x86_64),1)
	OS_SIZE = 64
	OS_ARCH = x86_64
endif

# Location of the CUDA Toolkit binaries and libraries
CUDA_PATH       ?= /data/cuda
CUDA_INC_PATH   ?= $(CUDA_PATH)/include
CUDA_BIN_PATH   ?= $(CUDA_PATH)/bin

ifeq ($(OS_SIZE),32)
  CUDA_LIB_PATH  ?= $(CUDA_PATH)/lib
else
  CUDA_LIB_PATH  ?= $(CUDA_PATH)/lib64
endif

# Common binaries
NVCC            ?= $(CUDA_BIN_PATH)/nvcc
GCC             ?= g++

# Extra user flags
EXTRA_NVCCFLAGS ?= --ptxas-options=-v
EXTRA_LDFLAGS   ?=
EXTRA_CCFLAGS   ?=

# CUDA code generation flags
GENCODE_SM30    := -gencode arch=compute_30,code=sm_30 -gencode arch=compute_35,code=sm_35

# OS-specific build flags
ifeq ($(OS_SIZE),32)
    LDFLAGS   := -L$(CUDA_LIB_PATH) -lcudart
    CCFLAGS   := -m32
else
    LDFLAGS   := -L$(CUDA_LIB_PATH) -lcudart
    CCFLAGS   := -m64
endif

# OS-architecture specific flags
ifeq ($(OS_SIZE),32)
      NVCCFLAGS := -m32
else
      NVCCFLAGS := -m64
endif

# Linux specific libraries and paths to include
LIBPATH_OPENGL  := -L/usr/X11R6/lib  -lGLU -lglut -lglfw lib/libGLEW.a

# Debug build flags
ifeq ($(dbg),1)
      CCFLAGS   += -g
      NVCCFLAGS += -g -G
      TARGET := debug
else
      TARGET := release
endif

# Common includes and paths for CUDA
INCLUDES      := -I$(CUDA_INC_PATH) -I. -I.. -I../../common/inc -I/home/stas/NVIDIA_GPU_Computing_SDK1/C/common/inc
LDFLAGS       += $(LIBPATH_OPENGL)

# Target rules
all: build

build: RayTracing

main.o: src/main.cu
	$(NVCC) $(NVCCFLAGS) $(EXTRA_NVCCFLAGS)  $(INCLUDES) -o $@ -c $<

manager.o: src/manager.cu
	$(NVCC) $(NVCCFLAGS) $(EXTRA_NVCCFLAGS)  $(INCLUDES) -o $@ -c $<

cuda_controller.o: src/cuda_controller.cu
	$(NVCC) $(NVCCFLAGS) $(EXTRA_NVCCFLAGS)  $(INCLUDES) -o $@ -c $<

vconsole.o: src/common/vconsole.cu
	$(NVCC) $(NVCCFLAGS) $(EXTRA_NVCCFLAGS)  $(INCLUDES) -o $@ -c $<

raytracer.o: src/cuda_files/raytracer.cu
	$(NVCC) $(NVCCFLAGS) $(EXTRA_NVCCFLAGS)  $(INCLUDES) -o $@ -c $<

RayTracing: main.o manager.o cuda_controller.o vconsole.o raytracer.o
	$(GCC) $(CCFLAGS) -o $@ $+ $(LDFLAGS) $(EXTRA_LDFLAGS)
	mkdir -p ../../bin/$(OSLOWER)/$(TARGET)
	cp $@ ../../bin/$(OSLOWER)/$(TARGET)

run: build
	./RayTracing

clean:
	rm -f RayTracing main.o manager.o vconsole.o raytracer.o cuda_controller.o 
